﻿Imports RoboRallyAPI
Imports System.Drawing

Public Class MyPlayerBrain : Implements IPlayer
	Private ReadOnly rand As New Random()

	Public ReadOnly Property Avatar As System.Drawing.Image Implements RoboRallyAPI.IPlayer.Avatar
		Get
			Return Nothing
		End Get
	End Property

	Public ReadOnly Property Name As String Implements RoboRallyAPI.IPlayer.Name
		Get
			Return "Bill Joy"
		End Get
	End Property

	Public Function Setup(ByVal map As RoboRallyAPI.GameMap, ByVal you As RoboRallyAPI.Player, ByVal robotStart() As System.Drawing.Point) As RoboRallyAPI.PlayerSetup Implements RoboRallyAPI.IPlayer.Setup
		Dim rtn As RoboRallyAPI.PlayerSetup
		rtn = New RoboRallyAPI.PlayerSetup(robotStart(0), RoboRallyAPI.MapSquare.DIRECTION.NORTH)
		Return rtn
	End Function

	Public Function Turn(ByVal map As RoboRallyAPI.GameMap, ByVal you As RoboRallyAPI.Player, ByVal allPlayers() As RoboRallyAPI.Player, ByVal cards() As RoboRallyAPI.Card) As RoboRallyAPI.PlayerTurn Implements RoboRallyAPI.IPlayer.Turn

		' if hurt bad, consider power down
		Dim powerDown As Boolean = False
		If (you.Damage > 5) AndAlso (rand.[Next](3) = 0) Then
			powerDown = True
		End If

		' get 40 sets, pick the one that's closest to the flag
		Dim best As Card() = Nothing
		Dim bestDiff As Integer = Integer.MaxValue
		Dim okDiff As Integer = rand.[Next](0, 3)
		Dim fs As Player.FlagState = you.FlagStates.FirstOrDefault(Function(fsOn) Not fsOn.Touched)
		Dim ptFlag As Point = If(fs Is Nothing, New Point(5, 6), fs.Position)
		For turnOn As Integer = 0 To 39
			' pick 5 (or fewer if locked) random cards
			Dim moveCards As Card() = New Card(4) {}
			Dim cardUsed As Boolean() = New Boolean(cards.Length - 1) {}
			For ind As Integer = 0 To 5 - you.NumLockedCards - 1
				While True
					Dim index As Integer = rand.[Next](cards.Length)
					If cardUsed(index) Then
						Continue While
					End If
					moveCards(ind) = cards(index)
					cardUsed(index) = True
					Exit While
				End While
			Next

			' add in the locked cards
			For ind As Integer = 5 - you.NumLockedCards To 4
				moveCards(ind) = you.Cards(ind)
			Next

			' run it
			Dim mp As Utilities.MovePoint = Utilities.CardDestination(map, you.Robot.Location, moveCards)
			If mp.Dead Then
				Continue For
			End If

			' if better than before, use it
			Dim diff As Integer = Math.Abs(ptFlag.X - mp.Location.MapPosition.X) + Math.Abs(ptFlag.Y - mp.Location.MapPosition.Y)
			If diff <= okDiff Then
				Return New PlayerTurn(moveCards, powerDown)
			End If
			If diff < bestDiff Then
				bestDiff = diff
				best = moveCards
			End If
		Next

		Return New PlayerTurn(best, powerDown)

	End Function
End Class
